const router = require("express").Router();
const sql = require("../mysql");
const { Campaign, CampaignTarget } = require("../mysql/collection/Campaign");
const Customer = require("../mysql/collection/Customer");
const uuid = require("uuid");

/**
 * @api {GET} /admin/crm/campaigns 获取营销活动列表
 * @apiName GetCampaigns
 * @apiGroup CRM-Campaign
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [type] 活动类型筛选
 * @apiParam {String} [status] 活动状态筛选
 * @apiParam {String} [createdBy] 创建人筛选
 * @apiParam {String} [keyword] 关键词搜索(活动名称)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 营销活动列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/campaigns", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, type, status, createdBy, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (type) query.type = type;
    if (status) query.status = status;
    if (createdBy) query.createdBy = createdBy;
    if (keyword) {
      query.name = { $regex: keyword, $options: 'i' };
    }
    
    const total = await Campaign.countDocuments(query);
    const list = await Campaign.find(query)
      .populate('createdBy', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取营销活动列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取营销活动列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/campaigns 创建营销活动
 * @apiName CreateCampaign
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} name 活动名称
 * @apiParam {String} type 活动类型
 * @apiParam {Object} content 活动内容
 * @apiParam {String} content.subject 主题
 * @apiParam {String} content.body 内容
 * @apiParam {String} [content.template] 模板
 * @apiParam {Date} [startDate] 开始日期
 * @apiParam {Date} [endDate] 结束日期
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 营销活动数据
 */
router.post("/campaigns", async (req, res) => {
  try {
    const campaignData = {
      ...req.body,
      campaignId: "CAM_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase(),
      createdBy: req.user._id // 使用ObjectId而不是adminid字符串
    };
    
    const campaign = await Campaign.create(campaignData);
    const populatedCampaign = await Campaign.findById(campaign._id)
      .populate('createdBy', 'adminname');
    
    res.send({
      code: "200",
      message: "创建营销活动成功",
      data: populatedCampaign
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建营销活动失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/campaigns/:id 获取营销活动详情
 * @apiName GetCampaignDetail
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} id 营销活动ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 营销活动详情
 */
router.get("/campaigns/:id", async (req, res) => {
  try {
    const campaign = await Campaign.findById(req.params.id)
      .populate('createdBy', 'adminname');
    
    if (!campaign) {
      return res.send({
        code: "404",
        message: "营销活动不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取营销活动详情成功",
      data: campaign
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取营销活动详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/campaigns/:id 更新营销活动信息
 * @apiName UpdateCampaign
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} id 营销活动ID
 * @apiParam {String} [name] 活动名称
 * @apiParam {String} [type] 活动类型
 * @apiParam {Object} [content] 活动内容
 * @apiParam {String} [status] 活动状态
 * @apiParam {Date} [startDate] 开始日期
 * @apiParam {Date} [endDate] 结束日期
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的营销活动数据
 */
router.put("/campaigns/:id", async (req, res) => {
  try {
    const campaign = await Campaign.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('createdBy', 'adminname');
    
    if (!campaign) {
      return res.send({
        code: "404",
        message: "营销活动不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新营销活动信息成功",
      data: campaign
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新营销活动信息失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/campaigns/:id/execute 执行营销活动
 * @apiName ExecuteCampaign
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} id 营销活动ID
 * @apiParam {Array} customerIds 目标客户ID列表
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 执行结果
 */
router.post("/campaigns/:id/execute", async (req, res) => {
  try {
    const { customerIds } = req.body;
    
    const campaign = await Campaign.findById(req.params.id);
    if (!campaign) {
      return res.send({
        code: "404",
        message: "营销活动不存在"
      });
    }
    
    if (campaign.status !== '草稿') {
      return res.send({
        code: "400",
        message: "只有草稿状态的活动才能执行"
      });
    }
    
    // 创建营销活动目标记录
    const targets = customerIds.map(customerId => ({
      campaignId: campaign._id,
      customerId,
      status: '已发送',
      sentTime: new Date()
    }));
    
    await CampaignTarget.insertMany(targets);
    
    // 更新活动状态
    await Campaign.findByIdAndUpdate(req.params.id, {
      status: '进行中',
      startDate: new Date()
    });
    
    res.send({
      code: "200",
      message: "营销活动执行成功",
      data: {
        targetCount: targets.length,
        executedAt: new Date()
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "执行营销活动失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/campaigns/:id/stats 获取营销活动统计
 * @apiName GetCampaignStats
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} id 营销活动ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 统计数据
 */
router.get("/campaigns/:id/stats", async (req, res) => {
  try {
    const campaign = await Campaign.findById(req.params.id);
    if (!campaign) {
      return res.send({
        code: "404",
        message: "营销活动不存在"
      });
    }
    
    const stats = await CampaignTarget.aggregate([
      { $match: { campaignId: campaign._id } },
      {
        $group: {
          _id: '$status',
          count: { $sum: 1 }
        }
      }
    ]);
    
    const totalTargets = await CampaignTarget.countDocuments({ campaignId: campaign._id });
    
    const statsObj = {
      total: totalTargets,
      sent: 0,
      opened: 0,
      clicked: 0,
      converted: 0
    };
    
    stats.forEach(stat => {
      switch (stat._id) {
        case '已发送':
          statsObj.sent = stat.count;
          break;
        case '已打开':
          statsObj.opened = stat.count;
          break;
        case '已点击':
          statsObj.clicked = stat.count;
          break;
        case '已转换':
          statsObj.converted = stat.count;
          break;
      }
    });
    
    res.send({
      code: "200",
      message: "获取营销活动统计成功",
      data: statsObj
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取营销活动统计失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/campaigns/:id 删除营销活动
 * @apiName DeleteCampaign
 * @apiGroup CRM-Campaign
 *
 * @apiParam {String} id 营销活动ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/campaigns/:id", async (req, res) => {
  try {
    const campaign = await Campaign.findByIdAndDelete(req.params.id);
    
    if (!campaign) {
      return res.send({
        code: "404",
        message: "营销活动不存在"
      });
    }
    
    // 同时删除相关的目标记录
    await CampaignTarget.deleteMany({ campaignId: req.params.id });
    
    res.send({
      code: "200",
      message: "删除营销活动成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除营销活动失败",
      error: error.message
    });
  }
});

module.exports = router;